package action;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.Helper;
import table.User;
import table.UserHandle;

/**
 * 用于改变用于密码的控制器
 */
@WebServlet("/SelfModifyPSW")
public class SelfModifyPSW extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelfModifyPSW() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 使用get访问该页无效
		response.getWriter().append("Please use POST method!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 用户登录有效性验证段
		User user = (User) request.getSession().getAttribute("user");
		if(user == null){
			request.getRequestDispatcher("index.jsp").forward(request, response);
			return;
		}
		
		String old_userid = user.getId();
		if(old_userid == null) {
			return;
		}
		String psw = Helper.getString(request.getParameter("txt_user_password"));
		String conPSW = Helper.getString(request.getParameter("txt_user_password_confirm"));
		
		if(!psw.equals(conPSW)) {
			response.getWriter().println("<script>window.location.href='user_self_info_modify.jsp';alert('Passwords are not equal!');</script>");
			return;
		}
		if(psw.length() < 6) {
			response.getWriter().println("<script>window.location.href='user_self_info_modify.jsp';alert('Password must at least 6 charaters!');</script>");
			return;
		}
		if(psw.length() > 16) {
			response.getWriter().println("<script>window.location.href='user_self_info_modify.jsp';alert('password too long!');</script>");
			return;
		}
		
		User newOne = new User();
		newOne.setId(user.getId());
		newOne.setName(user.getName());
		newOne.setTeamid(user.getTeamid());
		newOne.setPassword(psw);
		
		UserHandle handle = new UserHandle();
		if(handle.updateToDB(old_userid, newOne)) {
			// 如果修改成功则返回之前修改页面，并弹出修改成功
			response.getWriter().println("<script>window.location.href='user_self_info.jsp';alert('Successfully modified!');</script>");
		}else {
			// 如果修改失败则返回之前修改页面，并弹出修改失败
			response.getWriter().println("<script>window.location.href='user_self_info_modify.jsp';alert('Fail to modify!');</script>");
		}
	}

}
